﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using CRMAdminDashboard.CrmSvc;
using System.Collections;

namespace CRMAdminDashboard
{
    public partial class FormAssignRoles : Form, IUtilityForm
    {

        #region Constants

        private const string RES_ASSIGNFORM_FORMHELP = "RES_ASSIGNFORM_FORMHELP";
        private const string RES_ASSIGNFORM_ADDHELP = "RES_ASSIGNFORM_ADDHELP";
        private const string RES_ASSIGNFORM_REMOVEHELP = "RES_ASSIGNFORM_REMOVEHELP";
        private const string RES_ASSIGNFORM_MAKELIKEHELP = "RES_ASSIGNFORM_MAKELIKEHELP";

        #endregion

        #region Fields

        /// <summary>
        /// Static pointer to my console
        /// </summary>
        private static TextBox _logWindow;

        /// <summary>
        /// True when the parent form has ordered to close
        /// </summary>
        private bool _closeFromParent;

        /// <summary>
        /// Code behind
        /// </summary>
        private HelperAssignRoles _helper;

        #endregion

        #region Entry Points

        /// <summary>
        /// Standard constructor
        /// </summary>
        public FormAssignRoles(CachingCrmService svcHandle)
        {
            InitializeComponent();
            this._helper = new HelperAssignRoles(svcHandle);
            EnableControls();
            cbSelectRolesByUsers.SelectedIndex = 0;
            cbSelectUsersByRoles.SelectedIndex = 0;
            _logWindow = txtOutput;
        }

        /// <summary>
        /// Called by the Parent form when logging out. Will force this form shut.
        /// </summary>
        public void ParentClose()
        {
            this._closeFromParent = true;
            this.Close();
            this._closeFromParent = false;
        }

        /// <summary>
        /// Write on the console
        /// </summary>
        /// <param name="logInMain">Write also on the parent's console</param>
        public static void WriteLog(bool logInMain, string msg)
        {
            _logWindow.AppendText(msg);
            if (logInMain)
            {
                FormLogin.WriteLog(msg);
            }
        }

        /// <summary>
        /// Write an exception on the console
        /// </summary>
        /// <param name="logInMain">Write also on the parent's console</param>
        public static void WriteLog(bool logInMain, Exception ex)
        {
            ClearLog();
            WriteLog(logInMain, FormLogin.FormatException(ex) + Environment.NewLine + Environment.NewLine);
        }

        /// <summary>
        /// Clear the console
        /// </summary>
        public static void ClearLog()
        {
            _logWindow.Clear();
        }

        #endregion

        #region Events

        private void FormAssignRoles_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (!this._closeFromParent)
            {
                ((FormLogin)this.Owner).ForceLogout();
            }
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void FormAssignRoles_Load(object sender, EventArgs e)
        {
            lblHelpForm.Text = Program.GetResString(RES_ASSIGNFORM_FORMHELP);
            btnAddRoles.Text = Program.GetResString(RES_ASSIGNFORM_ADDHELP);
            btnRemoveRoles.Text = Program.GetResString(RES_ASSIGNFORM_REMOVEHELP);
            btnMakeLike.Text = Program.GetResString(RES_ASSIGNFORM_MAKELIKEHELP);
        }

        private void lstUsers_SelectedIndexChanged(object sender, EventArgs e)
        {
            int selected = lstUsers.SelectedItems.Count;
            if (selected == 0)
            {
                lblUsersSelected.Text = null;
            }
            else
            {
                lblUsersSelected.Text = selected.ToString() + " selected";
            }
            this.EnableControls();
        }

        private void lstRoles_SelectedIndexChanged(object sender, EventArgs e)
        {
            int selected = lstRoles.SelectedItems.Count;
            if (selected == 0)
            {
                lblRolesSelected.Text = null;
            }
            else
            {
                lblRolesSelected.Text = selected.ToString() + " selected";
            }
            this.EnableControls();
        }

        private void btnGetUsersRoles_Click(object sender, EventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                btnGetUsersRoles.Enabled = false;
                this._helper.GetUsersRoles(lstUsers, lstRoles);
                if (this._helper.BuFilter != null)
                {
                    StringBuilder sb = new StringBuilder();
                    sb.Append("Warning! BU Filter ON (");
                    foreach (BusinessUnit bu in this._helper.BuFilter.Values)
                    {
                        sb.Append(bu.Name + ", ");
                    }
                    sb.Length = sb.Length - 2;
                    sb.Append(")");
                    lblWarning.Text = sb.ToString();
                    this.btnSaveRolesUsers.Text = "Ex&port Filtered Roles with Associated Users as XML file...";
                    this.btnSaveUsersRoles.Text = "&Export Filtered Users with Associated Roles as XML file...";
                }
                else
                {
                    lblWarning.Text = null;
                    this.btnSaveRolesUsers.Text = "Ex&port All Roles with Associated Users as XML file...";
                    this.btnSaveUsersRoles.Text = "&Export All Users with Associated Roles as XML file...";
                }
            }
            finally
            {
                btnGetUsersRoles.Enabled = true;
                this.EnableControls();
                this.Cursor = Cursors.Default;
            }
        }

        private void btnSaveUsersRoles_Click(object sender, EventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                btnSaveUsersRoles.Enabled = false;
                this._helper.DumpUsersRoles();
            }
            finally
            {
                btnSaveUsersRoles.Enabled = true;
                this.Cursor = Cursors.Default;
            }
        }

        private void btnSaveRolesUsers_Click(object sender, EventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                btnSaveRolesUsers.Enabled = false;
                this._helper.DumpRolesUsers();
            }
            finally
            {
                btnSaveRolesUsers.Enabled = true;
                this.Cursor = Cursors.Default;
            }
        }

        private void btnSelectRolesByUsers_Click(object sender, EventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                btnSelectRolesByUsers.Enabled = false;
                this._helper.SelectRolesByUsers(new ArrayList(lstUsers.SelectedItems).Cast<SystemUser>(),
                    lstRoles, cbSelectRolesByUsers.SelectedIndex);
            }
            finally
            {
                btnSelectRolesByUsers.Enabled = true;
                this.Cursor = Cursors.Default;
            }
        }

        private void btnSelectUsersByRoles_Click(object sender, EventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                btnSelectUsersByRoles.Enabled = false;
                this._helper.SelectUsersByRoles(new ArrayList(lstRoles.SelectedItems).Cast<SystemRole>(),
                    lstUsers, cbSelectUsersByRoles.SelectedIndex);
            }
            finally
            {
                btnSelectUsersByRoles.Enabled = true;
                this.Cursor = Cursors.Default;
            }
        }

        private void btnMakeLike_Click(object sender, EventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                btnMakeLike.Enabled = false;
                this._helper.MakeLike(
                    new ArrayList(lstUsers.SelectedItems).Cast<SystemUser>(),
                    lstRoles);
            }
            finally
            {
                btnMakeLike.Enabled = true;
                this.Cursor = Cursors.Default;
            }
        }

        private void btnAddRoles_Click(object sender, EventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                btnAddRoles.Enabled = false;
                this._helper.AddRoles(
                    new ArrayList(lstUsers.SelectedItems).Cast<SystemUser>(),
                    new ArrayList(lstRoles.SelectedItems).Cast<SystemRole>(), true);
            }
            finally
            {
                btnAddRoles.Enabled = true;
                this.Cursor = Cursors.Default;
            }
        }

        private void btnRemoveRoles_Click(object sender, EventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                btnRemoveRoles.Enabled = false;
                this._helper.RemoveRoles(
                    new ArrayList(lstUsers.SelectedItems).Cast<SystemUser>(),
                    new ArrayList(lstRoles.SelectedItems).Cast<SystemRole>(), true);
            }
            finally
            {
                btnRemoveRoles.Enabled = true;
                this.Cursor = Cursors.Default;
            }
        }

        #endregion

        #region Local Methods

        /// <summary>
        /// Enable/disable controls accordingly
        /// </summary>
        private void EnableControls()
        {
            if (lstUsers.Items.Count > 0)
            {
                lblUsers.Enabled = true;
                lblRoles.Enabled = true;
                lblUsersSelected.Visible = true;
                lblRolesSelected.Visible = true;
                lstUsers.Enabled = true;
                lstRoles.Enabled = true;
                lblHelpForm.Visible = true;
                btnSaveUsersRoles.Visible = true;
                btnSaveRolesUsers.Visible = true;

                if (lstUsers.SelectedItems.Count > 0)
                {
                    btnSelectRolesByUsers.Visible = true;
                    cbSelectRolesByUsers.Visible = true;
                    btnMakeLike.Visible = true;
                    if (lstRoles.SelectedItems.Count > 0)
                    {
                        btnSelectUsersByRoles.Visible = true;
                        cbSelectUsersByRoles.Visible = true;
                        btnAddRoles.Visible = true;
                        btnRemoveRoles.Visible = true;
                    }
                    else
                    {
                        btnSelectUsersByRoles.Visible = false;
                        cbSelectUsersByRoles.Visible = false;
                        btnAddRoles.Visible = false;
                        btnRemoveRoles.Visible = false;
                    }
                }
                else
                {
                    btnSelectRolesByUsers.Visible = false;
                    cbSelectRolesByUsers.Visible = false;
                    btnMakeLike.Visible = false;
                    btnAddRoles.Visible = false;
                    btnRemoveRoles.Visible = false;
                    if (lstRoles.SelectedItems.Count > 0)
                    {
                        btnSelectUsersByRoles.Visible = true;
                        cbSelectUsersByRoles.Visible = true;
                    }
                    else
                    {
                        btnSelectUsersByRoles.Visible = false;
                        cbSelectUsersByRoles.Visible = false;
                    }
                }
            }
            else
            {
                btnSaveUsersRoles.Visible = false;
                btnSaveRolesUsers.Visible = false;
                lblHelpForm.Visible = false;
                lblUsers.Enabled = false;
                lblRoles.Enabled = false;
                lblUsersSelected.Visible = false;
                lblRolesSelected.Visible = false;
                lstUsers.Enabled = false;
                lstRoles.Enabled = false;
                btnSelectUsersByRoles.Visible = false;
                cbSelectUsersByRoles.Visible = false;
                btnSelectRolesByUsers.Visible = false;
                cbSelectRolesByUsers.Visible = false;
                btnAddRoles.Visible = false;
                btnRemoveRoles.Visible = false;
                btnMakeLike.Visible = false;
            }
        }

        #endregion

    }
}
